package com.cb.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cb.common.R;
import com.cb.dto.DishDto;
import com.cb.entity.Category;
import com.cb.entity.Dish;
import com.cb.mapper.DishMapper;
import com.cb.service.CategoryService;
import com.cb.service.DishFlavorService;
import com.cb.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {

    @Autowired
    private DishService dishService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private DishMapper dishMapper;

    /**
     * 新增菜品
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto){
        log.info(dishDto.toString());
        dishService.saveWithFlavor(dishDto);

        //清理某个分类下面的菜品缓存数据
        String key="dish_"+dishDto.getCategoryId()+"_"+dishDto.getStatus();
        redisTemplate.delete(key);

        return R.success("新增菜品成功！");
    }

    /**
     * 菜品信息分页查询
     */
    @GetMapping("/page")
    public R<IPage<DishDto>> page(int page, int pageSize, String name){
        //构造分页构造器
        Page<Dish> pageInfo = new Page<>(page,pageSize);
        Page<DishDto> dishDtoPage = new Page<>();
        dishService.getDish(pageInfo, name);

        //对象拷贝
        BeanUtils.copyProperties(pageInfo,dishDtoPage,"records");
        List<Dish> records = pageInfo.getRecords();
        List<DishDto> list=records.stream().map((item)->{
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item,dishDto);
            Long categoryId = item.getCategoryId();
            //根据id查分类对象
            Category category = categoryService.getById(categoryId);
            if (category!=null) {
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            return dishDto;
        }).collect(Collectors.toList());

        dishDtoPage.setRecords(list);
        return R.success(dishDtoPage);
    }

    /**
     * 修改菜品
     */
    //根据Id查询菜品信息与对应的口味信息(数据回显)
    @GetMapping("/{id}")
    public R<DishDto> getById(@PathVariable Long id){
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    //修改菜品信息
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto){
        dishService.updateWithFlavor(dishDto);

        //清理所有菜品缓存数据
        /*Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);*/

        //清理某个分类下面的菜品缓存数据
        String key="dish_"+dishDto.getCategoryId()+"_"+dishDto.getStatus();
        redisTemplate.delete(key);

        return R.success("修改菜品成功！");
    }

    /**
     * 起售停售菜品
     */
    @PostMapping("/status/{status}")
    public R<String> sale(@PathVariable int status,String[] ids){
        log.info("status:{},ids:{}",status,ids);
        dishService.sale(status,ids);

        //清理某个分类下面的菜品缓存数据
        Set<String> dishId = getByDishId(ids,null);
        redisTemplate.delete(dishId);

        return R.success("修改成功！");
    }

    /**
     * 删除菜品
     */
    @DeleteMapping
    public R<String> deleteDish(@RequestParam List<String> ids){
        log.info("ids:{}",ids.toString());
        dishService.deleteDish(ids);

        //清理某个分类下面的菜品缓存数据
        Set<String> dishId = getByDishId(null,ids);
        redisTemplate.delete(dishId);

        return R.success("删除成功！");
    }

    /**
     * 根据分类查询菜品信息
     */
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish){
        List<DishDto> dishDtoList=null;
        //动态构造Key
        String key="dish_"+dish.getCategoryId()+"_"+dish.getStatus();
        //先从redis中获取缓存数据
        dishDtoList=(List<DishDto>)redisTemplate.opsForValue().get(key);
        if(dishDtoList!=null){
            //如果存在，则直接返回，无需查询数据库
            return R.success(dishDtoList);
        }
        //如果不存在，则查询数据库，并且将查询到的菜品数据添加到缓存中
        dishDtoList = dishService.getListByCategoryId(dish);
        redisTemplate.opsForValue().set(key,dishDtoList,60, TimeUnit.MINUTES);
        return R.success(dishDtoList);
    }

    //根据dishid获得categoryid
    public Set<String> getByDishId(String []ids,List<String> ids2){
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        if (ids==null) {
            queryWrapper.in(Dish::getId,ids2);
        }
        if (ids2==null) {
            queryWrapper.in(Dish::getId,ids);
        }
        List<Dish> dishes = dishMapper.selectList(queryWrapper);
        Set<String> dishCategoryId=new HashSet<>();
        for (Dish dish : dishes) {
            dishCategoryId.add("dish_"+dish.getCategoryId()+"_1");
        }
        return dishCategoryId;
    }

}